'use strict';

import React from 'react'
import {
  StyleSheet, Text, View, TextInput, Dimensions, AlertIOS
} from 'react-native'

//第三方组件
import {CountDownText} from 'react-native-sk-countdown'
//var {CountDownText} = require('react-native-sk-countdown');
import Button from 'react-native-button'

//自定义组件
import _styles from '../common/styles'
import Header from '../common/header'
import request from '../common/request'
import config from '../common/config'

var width = Dimensions.get('window').width  //获取屏幕的宽度

//登录页面
const Login = React.createClass({
  getInitialState(){
    return {
      phoneNumber: '',
      verifyCode: '',
      sendCode: false, //是否已经发送过了验证码
      countingDown: false, //倒计时是否已完成
    }
  },

  //获取短信验证码
  _sendVerifyCode(){
    let phone = this.state.phoneNumber;
    if (phone.trim() === '') {
      return AlertIOS.alert('请输入手机号码');
    }
    request.post(config.api.base + config.api.signup, {phoneNumber: phone})
      .then((data) => {
        if (data && data.success) {  //请求成功
          this.setState({sendCode: true, countingDown: false});
        }
        else {
          AlertIOS.alert('获取短信验证码失败，请稍后再试');
        }
      })
  },

  //登录
  _login(){
    let phone = this.state.phoneNumber;
    let code = this.state.verifyCode;
    if (phone.trim() === '' || code.trim()==='') {
      return AlertIOS.alert('手机号码或短信验证码不能为空');
    }
    request.post(config.api.base + config.api.verify, {phoneNumber: phone, verifyCode:code})
      .then((data) => {
        if (data && data.success) {  //请求成功，调用属性传入的afterLogin方法
          this.props.afterLogin(data.data);
        }
        else {
          AlertIOS.alert('登录失败，请稍后再试');
        }
      })
  },

  render() {
    return (
      <View style={_styles.fContainer}>
        <Header title="快速登录" navigator={this.props.navigator} bgColor="#f9f9f9" color="#000"/>
        <TextInput placeholder='输入手机号'
                   autoCapitalize={'none'}  //不纠正大小写
                   autoCorrect={false}  //不纠正内容的正确性
                   keyboardType={'number-pad'} //数字键盘
                   style={_styles.textInput}
                   maxLength={11}
                   onChangeText={(text)=>{
                     this.setState({ phoneNumber:text })
                   }}
        ></TextInput>
        {
          this.state.sendCode ?
            <View style={styles.verifyCode}>
              <TextInput placeholder='输入短信验证码'
                         autoCapitalize={'none'}  //不纠正大小写
                         autoCorrect={false}  //不纠正内容的正确性
                         keyboardType={'number-pad'} //数字键盘
                         style={[_styles.textInput,{width:width-152}]}
                         maxLength={6}
                         onChangeText={(text)=>{
                           this.setState({ verifyCode:text })
                         }}
              ></TextInput>
              {
                this.state.countingDown
                  ? <Button onPress={this._sendVerifyCode} style={_styles.countBtn}>重新获取验证码</Button>
                  : <CountDownText
                    style={styles.countDown}
                    countType='seconds' // 计时类型：seconds / date
                    auto={true} // 自动开始
                    afterEnd={()=>{this.setState({countingDown:true})} } // 结束回调
                    timeLeft={10} // 正向计时 时间起点为0秒
                    step={-1} // 计时步长，以秒为单位，正数则为正计时，负数为倒计时
                    startText='获取验证码' // 开始的文本
                    endText='获取验证码' // 结束的文本
                    intervalText={(sec) => sec + '秒重新获取'} // 定时的文本回调
                  />
              }
            </View>
            : null
        }
        {
          this.state.sendCode //是否有发送验证码
            ? <Button onPress={this._login} style={_styles.btn}>登录</Button>
            : <Button onPress={this._sendVerifyCode} style={_styles.btn}>获取验证码</Button>
        }
      </View>
    )
  }
})

const styles = StyleSheet.create({
  verifyCode: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 5,
  },
  countDown: {
    height: 40,
    backgroundColor: '#ccc',
    lineHeight: 40,
    width: 150,
    color: '#666',
    textAlign: 'center',
  },

});

module.exports = Login